package com.catbad.util;

import java.security.MessageDigest;

public class Tools {

    //******************Begin  MD5******************
    public final static String initPwd="d3c70526aff576899584e95babfb4085";

    public static String getMd5(String pwd) throws Exception
    {
        //对明文进行第一次加密
        String md5pwd1=Tools.MD5Encode(pwd);
        //生成混淆密文
        String pwd2=md5pwd1+"趙客ъф縵しゎと胡纓,吳鉤霜ùǎóê雪明,事了ㄜㄞㄏㄈㄥㄗ拂衣もフヱヴスニ去,深藏功与名,"+md5pwd1;
        //生成混淆密文
        String md5pwd2=Tools.MD5Encode(pwd2);
        return md5pwd2;


    }

    /**
     * MD5的两个特性
     * 1.单向加密:可以从明文通过加密,生成密文,但是不可以从密文还原成明文--不可逆性
     * 2.统一个字符串,无论加密多少次,得到的密文始终是相同
     */
    private final static String[] hexDigits = {
            "0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "a", "b", "c", "d", "e", "f"
    };

    /**
     * 转换字节数组为16进制字串
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b)
    {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
        {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }
    /**
     * 转换字节为16进制字符串
     * @param b byte
     * @return String
     */
    private static String byteToHexString(byte b)
    {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    /**
     * 得到MD5的秘文密码
     * @param origin String
     * @throws Exception
     * @return String
     */
    private static String MD5Encode(Object origin) throws Exception
    {
        String resultString = null;
        try
        {
            resultString=new String(origin.toString());
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
            return resultString;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    //******************END  MD5******************
}
